#include<unistd.h>
#include<iostream>
#include<stdlib.h>

int main()
{
  std::cerr<<"-------- test_cgi Start --------"<<std::endl;


  std::string method = getenv("Method");
  std::string param;
   
  std::cerr<<"Method="<<getenv("Method")<<std::endl;

  if( method == "GET")
  {//通过环境变量获得数据
    param = getenv("Param");
  }
  else if( method == "POST" )
  {//通过管道获得数据
    int content_length=atoi(getenv("Content_Length")); 
    std::cerr<<"Get Content-Length="<<content_length<<std::endl;
    char buffer[1024]={0};
    int total =0;
    int actual_count=0;
    int expect_count= content_length>sizeof(buffer) ? sizeof(buffer):content_length;
    while((actual_count=read(0,buffer,expect_count)) > 0)
    {
      buffer[actual_count] = 0;
      param+=buffer;
      buffer[0]=0;
      total+=actual_count;
      expect_count= content_length-total>sizeof(buffer) ? sizeof(buffer):content_length-total;
    }

  }
  std::cout<<param;
  std::cerr<<param<<std::endl; 

  std::cerr<<"-------- test_cgi End --------"<<std::endl;


  return 0;
   
}
